﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EzDesk.Core.Interface;
using EzDesk.Core.Model;
using EzDesk.Core.ServiceImpl.Services;
using EzDesk.Utility.Log;

using EzDesk.Utility.ServiceStatusInfo;
using EzDesk.Utility.Extensions;
using EzDesk.Utility.Web.Extensions;

namespace EzDesk.ServiceHost.Controllers
{
    
    public partial class CoreController : EzDeskController
    {
        public ICoreClientService _coreClientService = new CoreClientService();

        [HttpGet]
        public ActionResult Error()
        {
            return View();
        }

        //
        // GET: /Core/TestLogin
        // RETURN_TYPE: StatusInfo

        [HttpGet]
        public JsonResult TestLogin()
        {
            var statusInfo = new StatusInfo(ServiceStatus.Success, "已登录");
            return Json(statusInfo, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult CheckIsOutOfPeriod()
        {
            var isOutOfPeriod = _coreClientService.CheckOutOfPeriod();
            var result = new StatusInfo() { Data = isOutOfPeriod };
            return Json(result);
        }

        [HttpPost]
        [EzAuthorize]
        public JsonResult UserHasPermission(string permissionStr)
        {
            return Json(_coreAppService.UserHasPermission(permissionStr, CurrentUserId));
        }

        #region [ Globle Info ]

        //
        // GET: /Core/OrganizationInfo
        // RETURN_TYPE: Organization

        [HttpGet]
        public JsonResult OrganizationInfo()
        {
            return Json(
                _coreClientService.GetOrganizationInfo(),
                JsonRequestBehavior.AllowGet
                );
        }

        //
        // POST: /Core/DoUpdateOrganizationInfo
        // RETURN_TYPE: StatusInfo

        [HttpPost]
        public JsonResult DoUpdateOrganizationInfo(string fullName, string shortName)
        {
            var statusInfo = new StatusInfo("更新公司信息完成");
            try
            {
                if (string.IsNullOrEmpty(fullName)) throw new ApplicationException("名称不能为空");
                if (string.IsNullOrEmpty(shortName)) throw new ApplicationException("名称不能为空");
                var org = _coreClientService.GetOrganizationInfo();
                org.FullName = fullName.HtmlEncode();
                org.ShortName = shortName.HtmlEncode();
                _coreClientService.UpdateOrganizationInfo(org);
            }
            catch (ApplicationException ex)
            {
                statusInfo = new StatusInfo(ex);
            }
            catch (Exception ex)
            {
                statusInfo = new StatusInfo(ServiceStatus.Error, "更新出错");
            }
            return Json(statusInfo);
        }

        #endregion

        #region [ App Functions ]
        //
        // GET: /Core/AppFunctions
        // RETURN_TYPE: IList<AppFunction>

        [HttpGet]
        [EzAuthorize]
        public JsonResult AllAppFunctions()
        {
            return Json(
                _coreClientService.GetAllAppFunctions(CurrentUserId),
                JsonRequestBehavior.AllowGet
                );
        }


        //
        // GET: /Core/AllAppFunctionTypes
        // RETURN_TYPE: IList<AppFunctionType>

        [HttpGet]
        [EzAuthorize]
        public JsonResult AllAppFunctionTypes()
        {
            return Json(
                _coreClientService.GetAllAppFunctionTypes(CurrentUserId),
                JsonRequestBehavior.AllowGet
                );
        }

        //
        // GET: /Core/AppFunctionsByTypeName
        // RETURN_TYPE: IList<AppFunction>

        [HttpGet]
        [EzAuthorize]
        public JsonResult AppFunctionsByTypeName(string appFunctionTypeName)
        {
            return Json(
                _coreClientService.GetAppFunctionsByTypeName(CurrentUserId, appFunctionTypeName),
                JsonRequestBehavior.AllowGet
                );
        }



        //
        // GET: /Core/AllAppFunctionCategories
        // RETURN_TYPE: IList<AppFunctionType>

        [HttpGet]
        [EzAuthorize]
        public JsonResult AllAppFunctionCategories()
        {
            return Json(
                _coreClientService.GetAllAppFunctionCategories(CurrentUserId),
                JsonRequestBehavior.AllowGet
                );
        }

        //
        // GET: /Core/AppFunctionsByCategoryName
        // RETURN_TYPE: IList<AppFunction>

        [HttpGet]
        [EzAuthorize]
        public JsonResult AppFunctionsByCategoryName(string name)
        {
            return Json(
                _coreClientService.GetAppFunctionsByCategoryName(CurrentUserId, name),
                JsonRequestBehavior.AllowGet
                );
        }


        //
        // GET: /Core/AppFunctionShortcutIds
        // RETURN_TYPE string

        [HttpGet]
        [EzAuthorize]
        public JsonResult AppFunctionShortcutIds()
        {
            return Json(
                _coreClientService.GetAppFunctionShortcutIds(CurrentUserId),
                JsonRequestBehavior.AllowGet
                );
        }

        //
        // POST: /Core/
        // RETURN_TYPE: StatusInfo

        [HttpPost]
        [EzAuthorize]
        public JsonResult UpdateAppFunctionShortcutSequnce(string shortCutIdSequnces)
        {
            _coreClientService.UpdateAppFunctionShortcutSequnce(CurrentUserId, shortCutIdSequnces);
            var statusInfo = new StatusInfo();
            return Json(statusInfo);
        }



        #endregion

        #region [ Feed Methods]

        //
        //Get: /Core/GetFeeds
        // RETURN_TYPE: FeedCollection
        [HttpGet]
        [EzAuthorize]
        public JsonResult GetFeeds(long? fromTicks = null, long? toTicks = null)
        {
            //LogEx.TRACE("CoreController", "GetFeeds 开始");
            DateTime? from = null, to = null;
            if (fromTicks.HasValue)
            {
                from = fromTicks.Value.FromTicks();
            }
            if (toTicks.HasValue)
            {
                to = toTicks.Value.FromTicks();
            }
            var feedList = _coreClientService.GetFeeds(CurrentUserId, from, to);
            //LogEx.TRACE("CoreController", "GetFeeds 结束");
            return Json(feedList, JsonRequestBehavior.AllowGet);
        }

        //
        // POST: /Core/UpdateFeedStatus
        // RETURN_TYPE: StatusInfo

        [HttpPost]
        [EzAuthorize]
        public JsonResult UpdateFeedStatus(Guid feedId, bool? isRead, bool? isMark, bool? isAvailable, string memberstring)
        {
            var feeds = new List<FeedStatus>()
                            {
                                new FeedStatus()
                                    {
                                        FeedId = feedId,
                                        IsAvailable = isAvailable,
                                        IsMark = isMark,
                                        IsRead = isRead,
                                    }
                            };
            _coreClientService.UpdateFeedStatus(feeds, memberstring);
            var statusInfo = new StatusInfo();
            return Json(statusInfo);
        }

        // 针对某条Feed的"我知道了"链接~~
        // POST: /Core/ConfirmNotification
        // RETURN_TYPE: StatusInfo

        [HttpPost]
        [EzAuthorize]
        public JsonResult ConfirmNotification(Guid feedId)
        {
            var feedStatus = new FeedStatus
                                 {
                                     FeedId = feedId,
                                     IsAvailable = false,
                                 };
            _coreClientService.UpdateFeedStatus(
                new List<FeedStatus> {feedStatus}, 
                CurrentUserId.ToString());
            var statusInfo = new StatusInfo();
            return Json(statusInfo);
        }

        #endregion

        #region [ UserProfile Method ]

        //
        // GET: /Core/GetAllPositions
        // RETURN_TYPE: List<Position>
        [HttpGet]
        [EzAuthorize]
        public JsonResult AllPositions()
        {
            return Json(
                _coreAppService.GetPostions(),
                JsonRequestBehavior.AllowGet
                );
        }

        //
        // GET: /Core/GetAllDepts
        // RETURN_TYPE: List<Dept>
        [HttpGet]
        [EzAuthorize]
        public JsonResult AllDepts()
        {
            return Json(
                _coreAppService.GetAllDepts(),
                JsonRequestBehavior.AllowGet
                );
        }

        [HttpPost]
        [EzAuthorize]
        public JsonResult CreateDept(string deptName)
        {
            var statusInfo = new StatusInfo("创建部门完成");
            try
            {
                _coreAppService.CreateDept(deptName, CurrentUserId);
            }catch(Exception ex)
            {
                statusInfo = new StatusInfo(ex);
            }
            return Json(statusInfo);
        }

        [HttpPost]
        [EzAuthorize]
        public JsonResult RemoveDept(Guid deptId)
        {
            var statusInfo = new StatusInfo("部门已删除");
            try
            {
                _coreAppService.RemoveDept(deptId, CurrentUserId);
            }
            catch (Exception ex)
            {
                statusInfo = new StatusInfo(ex);
            }
            return Json(statusInfo);
        }

        [HttpPost]
        [EzAuthorize]
        public JsonResult CreatePosition(string positionName)
        {
            var statusInfo = new StatusInfo("创建职位完成");
            try
            {
                _coreAppService.CreatePosition(positionName, CurrentUserId);
            }
            catch (Exception ex)
            {
                statusInfo = new StatusInfo(ex);
            }
            return Json(statusInfo);
        }

        [HttpPost]
        [EzAuthorize]
        public JsonResult RemovePosition(Guid positionId)
        {
            var statusInfo = new StatusInfo("职位已删除");
            try
            {
                _coreAppService.RemovePosition(positionId, CurrentUserId);
            }
            catch (Exception ex)
            {
                statusInfo = new StatusInfo(ex);
            }
            return Json(statusInfo);
        }


        //
        // GET: /Core/PermissionGroups
        // RETURN_TYPE: List<Groups>
        [HttpGet]
        [EzAuthorize]
        public JsonResult PermissionGroups()
        {
            return Json(
                _coreClientService.GetPermissionGroups(),
                JsonRequestBehavior.AllowGet
                );
        }



        //
        // GET: /Core/UserPermissionGroups
        // RETURN_TYPE: List<Group>
        [HttpGet]
        [EzAuthorize]
        public JsonResult UserPermissionGroups(Guid userId)
        {
            return Json(
                _coreClientService.GetUserPermissionGroups(userId),
                JsonRequestBehavior.AllowGet
                );
        }

        //
        // GET: /Core/DoUpdateUserGroups
        // RETURN_TYPE: StatusInfo
        [HttpPost]
        [EzAuthorize]
        public JsonResult DoUpdateUserGroups(string groupIdStrs, Guid userId)
        {
            var statusInfo = new StatusInfo("更新用户组完成");
            try
            {
                var groupIdList = groupIdStrs.Split(',').Select(p => new Guid(p)).ToList();
                _coreClientService.UpdateUserGroups(groupIdList, userId);
            }
            catch (Exception ex)
            {
                statusInfo = new StatusInfo(ServiceStatus.Error, "更新用户组出错");
            }
            return Json(statusInfo);
        }

        //
        // GET: /Core/CurrentUser
        // RETURN_TYPE: SimpleUser

        [HttpGet]
        [EzAuthorize]
        public JsonResult CurrentUser()
        {
            return Json(
                _coreClientService.GetSimpleUserById(CurrentUserId),
                JsonRequestBehavior.AllowGet
                );
        }

        //
        // GET: /Core/UserProfileById
        // RETURN_TYPE: UserProfile

        [HttpGet]
        [EzAuthorize]
        public JsonResult UserProfileById(Guid userId)
        {
            return Json(
                _coreClientService.GetUserProfileById(userId),
                JsonRequestBehavior.AllowGet
                );
        }

        //
        // GET: /Core/SimpleUserById
        // RETURN_TYPE: SimpleUser

        [HttpGet]
        [EzAuthorize]
        public JsonResult SimpleUserById(Guid userId)
        {
            return Json(
                _coreClientService.GetSimpleUserById(userId),
                JsonRequestBehavior.AllowGet
                );
        }

        //
        // GET: /Core/SimpleUserInfos
        // RETURN_TYPE: IList<SimpleUser>

        [HttpGet]
        [EzAuthorize]
        public JsonResult SimpleUserInfos(string memberstring)
        {
            return Json(
                _coreClientService.GetSimpleUserInfos(memberstring),
                JsonRequestBehavior.AllowGet
                );
        }

        //
        // GET: /Core/DeptById
        // RETURN_TYPE: Dept

        [HttpGet]
        [EzAuthorize]
        public JsonResult DeptById(Guid deptId)
        {
            return Json(
                _coreClientService.GetDeptById(deptId),
                JsonRequestBehavior.AllowGet
                );
        }

        #endregion

        #region [ Clients Management ]
        //
        // GET: /Core/ClientBaseUrl
        // RETURN_TYPE: string

        [HttpGet]
        [EzAuthorize]
        public JsonResult ClientBaseUrl()
        {
            return Json(
                _coreClientService.GetClientBaseUrl(),
                JsonRequestBehavior.AllowGet
                );
        }
        #endregion

    }
}
